<?php

namespace backend\extensions;

use yii\rest\Controller;
use backend\extensions\HttpSignAuth;
use backend\extensions\HttpTokenAuth;
use yii\filters\Cors;
use yii\base\DynamicModel;

/**
 * Desc 所有请求的基类(必须继承)
 * @author HUI
 */
class ApiBaseController extends Controller
{

    //合法参数
    public $params = [];

    public function init()
    {
        parent::init();
    }

    /**
     * 重写 behaviors
     */
    public function behaviors()
    {
        return [
            //跨域处理
            'corsFilter' => [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Allow-Credentials' => false,
                    'Access-Control-Max-Age' => 86400,
                    'Access-Control-Expose-Headers' => [],
                ],
            ],
            'tokenValidate' => [
                //除登录接口外，其余接口均需要校验token
                'class' => HttpTokenAuth::className(),
                'optional' => ['config/admin/login', 'index/default', 'config/admin/captcha', 'index/index', 'home/home/index'],
            ],
        ];
    }

    public function actions()
    {
        $actions = parent::actions();
        return $actions;
    }

    public function beforeAction($action)
    {
        parent::beforeAction($action);
        return \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    }

    /**
     * @desc 前端传参规则校验
     * @param  array $params 参数
     * @param  array $rules 规则
     * * */
    protected function validateParams($params, $rules)
    {
        $model = DynamicModel::validateData($params, $rules);
        if ($model->hasErrors()) {
            $errors = [];
            foreach ($model->getErrors() as $value) {
                $errors[] = $value[0];
            }
            return implode(',', $errors);
        }
        foreach ($params as $field => $value) {
            foreach ($rules as $val) {
                if (empty(is_array($val))) {
                    return '规则属性字段必须是数组';
                }
                //默认值
                if ($val[1] == 'default') {
                    foreach ($val[0] as $v) {
                        if(!isset($params[$v])) {
                            $this->params[$v] = '';
                        } elseif(empty($params[$v]) && $params[$v] != 0) {
                            $this->params[$v] = $val['value'];
                        } else {
                            $this->params[$v] = $params[$v];
                        }
                    }
                    continue;
                }
                if (in_array($field, $val[0])) {
                    $this->params[$field] = $value;
                }
            }
        }
        return '';
    }

    /**
     * @desc   json出错返回

     * @param  string $msg
     * @return json
     */
    protected function jsonError($message = '请求异常', $data = [])
    {
        return ['code' => 1, 'message' => $message, 'data' => $data];
    }

    /**
     * @desc   json成功返回
     * @param  array $data
     * @return json
     */
    protected function jsonSuccess($data = [], $message = '请求成功')
    {
        return ['code' => 0, 'message' => $message, 'data' => $data];
    }
}
